package com.example.baselibrary.db.dao;

import android.text.TextUtils;

import com.example.baselibrary.db.BTDBHelper;
import com.example.baselibrary.db.table.FileSearchHistoryTable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cc.vv.lklibrary.db.dao.DBBaseTableDao;
import cc.vv.lklibrary.db.help.DBBaseOpenHelper;

/**
 * Date 2018/4/2
 * Describe
 *
 * @auther liuxin
 */

public class FileSearchHistoryDao extends DBBaseTableDao<FileSearchHistoryTable, String> {

    public FileSearchHistoryDao(DBBaseOpenHelper openHelper) {
        super(openHelper);
    }

    private static FileSearchHistoryDao mInstance;

    public static FileSearchHistoryDao getInstance() {
        if (null == mInstance) {
            synchronized (FileSearchHistoryDao.class) {
                if (null == mInstance) {
                    mInstance = new FileSearchHistoryDao(BTDBHelper.getInstance());
                }
            }
        }
        return mInstance;
    }

    /**
     * 查询数据库
     */
    public ArrayList<FileSearchHistoryTable> queryAllSearchHistory() {
        ArrayList<FileSearchHistoryTable> fileSearchHistoryTables = (ArrayList<FileSearchHistoryTable>) queryAll();
        Collections.reverse(fileSearchHistoryTables);
        return fileSearchHistoryTables;
    }

    /**
     * 插入搜索记录
     *
     * @param searchKey 搜索关键字
     */
    public void insertSearchHistory(String searchKey) {
        if (TextUtils.isEmpty(searchKey)) {
            return;
        }
        List<FileSearchHistoryTable> fileSearchHistoryTables = queryAll();
        for (FileSearchHistoryTable searchHistoryKey : fileSearchHistoryTables) {
            if (searchKey.equals(searchHistoryKey.searchKey)) {
                deleteById(searchHistoryKey.searchKey);
                break;
            }
        }
        insert(new FileSearchHistoryTable(searchKey));
    }
}
